package com.gengzp.permission.core.impl;

import com.gengzp.permission.annotation.AuthIgnore;
import com.gengzp.permission.core.PermissionExemptUrisFetcher;
import com.gengzp.permission.core.PermissionVerificationProcessor;
import com.gengzp.permission.exception.PermissionException;
import com.gengzp.permission.factory.PermissionInstanceFactory;
import com.gengzp.permission.model.UserPrincipalModel;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.util.Objects;

/**
 * @ClassName PermissionVerificationProcessorImpl
 * @Description 权限验证处理器实现类
 * @Author gengzp
 * @Date 2025/8/13 23:53
 */
@Component
public class PermissionVerificationProcessorImpl implements PermissionVerificationProcessor {

    @Autowired
    private PermissionInstanceFactory permissionInstanceFactory;

    @Override
    public Boolean verifyRequestUriIsPermissionExempt(String requestUri) {
        for (PermissionExemptUrisFetcher fetcher : permissionInstanceFactory.getAllPermissionExemptUrisFetchers()) {
            if (fetcher.getPermissionExemptUris().contains(requestUri)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean verifyRequestMethodHasAuthIgnoreAnnotation(Object handler) {
        if (handler instanceof HandlerMethod) {
            return Objects.nonNull(((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class));
        }
        return false;
    }

    @Override
    public UserPrincipalModel parseAndVerifyRequestAuthentication(HttpServletRequest request, Object handler) throws PermissionException {
        return permissionInstanceFactory.getPermissionTokenProcessor().parseAndVerifyRequestAuthentication(request, handler);
    }


}
